package vtt.android.cartoon_video.activities;

import org.json.JSONObject;

import vtt.android.cartoon_video.Constants;
import vtt.android.cartoon_video.MyPushReceiver;
import vtt.android.cartoon_video.R;
import vtt.android.cartoon_video.dialogs.DialogManager;
import vtt.android.cartoon_video.dialogs.DialogManager.IListDialogListener;
import vtt.android.cartoon_video.entities.CommonHashMap;
import vtt.android.cartoon_video.entities.PageInfo;
import vtt.android.cartoon_video.fragments.BaseMainFragment;
import vtt.android.cartoon_video.fragments.BaseMainFragment.OnItemSelectedListener;
import vtt.android.cartoon_video.fragments.BaseWebFragment;
import vtt.android.cartoon_video.fragments.DetailFragment;
import vtt.android.cartoon_video.utils.CommonUtils;
import vtt.android.cartoon_video.utils.JazzyViewPager;
import vtt.android.cartoon_video.utils.JazzyViewPager.TransitionEffect;
import vtt.android.cartoon_video.widgets.sliding_tab.SlidingTabLayout;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

public class MainActivity extends BaseActivity implements 
        OnItemSelectedListener {

    private static final int DEFAULT_TRANSITION_INDEX = 1; // 1 : CUBE_OUT
    
    private SectionsPagerAdapter mSectionsPagerAdapter;
    public JazzyViewPager mJazzyViewPager;
    public DialogManager mDialogManager;
    private SparseArray<PageInfo> mPageMap;
    private SlidingMenu mSlidingMenu;
    private TransitionEffect mTransitionEffect = TransitionEffect.Standard;
    private SharedPreferences mSharedPreferences;
    private ImageView mImgBackground;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lich_phat_song);
        mDialogManager = new DialogManager(mContext);
        
        mImgBackground = (ImageView) findViewById(R.id.img_bacground);
        
        // init page mapping
        mPageMap = CommonHashMap.getPageMap(mContext);
        mSharedPreferences = CommonUtils.getSharedPreferences(mContext);
        // setup sliding menu
        setupLeftSlidingMenu();
        
        mTransitionEffect = getTransitionEffect();
        setupJazzyViewPager(mTransitionEffect);
        setupSlidingTab();
        
        // check network
        if (!VttUtils.checkNetworkConnection(this)) {
            mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR, getString(R.string.msg_title_notice),
                    getString(R.string.msg_network_error), null);
        }
        
        // check GCM push notification
        checkPushGCM(getIntent());
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        changeBackground();
    }
    
    /**
     * setup sliding tab
     */
    private void setupSlidingTab() {
        final SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setCustomTabView(R.layout.tabview, R.id.tabview_text);
        mSlidingTabLayout.setViewPager(mJazzyViewPager);
        mSlidingTabLayout.setSelectedTextColor(R.color.tab_text_color_active);
        mSlidingTabLayout.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                log.d("VTT>>> onPageSelected " + " mSlidingTabLayout " + position);
                
                switch (position) {
                case 0:
                    mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
                    break;
                default:
                    mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
                    break;
                }
                // GA
                VttGA.sendEvent(mContext, "onPageSelected", mPageMap.get(position).title, null, 0);
            }
            
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                
            }
            
            @Override
            public void onPageScrollStateChanged(int arg0) {
                
            }
        });
        
        mSlidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                if(position < CommonHashMap.mTabColors.length){
                    return getResources().getColor(CommonHashMap.mTabColors[position]);
                }
                return CommonHashMap.mTabColors[0];
            }

            @Override
            public int getDividerColor(int position) {
                return getResources().getColor(R.color.tab_divider);
            }
        });
    }

    /**
     * setup sliding menu
     */
    private void setupLeftSlidingMenu() {
        mSlidingMenu = new SlidingMenu(this);
        mSlidingMenu.setMode(SlidingMenu.LEFT);
        
        mSlidingMenu.setMenu(R.layout.menu_left);
//        mSlidingMenu.setSecondaryMenu(R.layout.menu_left);
        
        mSlidingMenu.setShadowDrawable(R.drawable.shadow);
//        mSlidingMenu.setSecondaryShadowDrawable(R.drawable.shadow_right);
        
        mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        mSlidingMenu.setBehindScrollScale(0.3f);
        mSlidingMenu.setFadeDegree(0.7f);
        mSlidingMenu.setTouchmodeMarginThreshold(30);
        mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        mSlidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        
        // check first start for opening menu
        SharedPreferences sharePref = CommonUtils.getSharedPreferences(this);
        boolean isFirstStart = sharePref.getBoolean(Constants.SHARE_IS_FIRST_START, true);
        if(isFirstStart){
            
            mSlidingMenu.showMenu();
            /*mSlidingMenu.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSlidingMenu.showContent(true);
                }
            }, 5000);*/// 5 seconds
            
            setupPageTransition();
            
            // update first start value
            sharePref.edit().putBoolean(Constants.SHARE_IS_FIRST_START, false).commit();
        } 
    }
    
    /**
     * check PUSH GCM
     */
    private void checkPushGCM(Intent intent) {
        log.d("VTT>>> checkPushGCM ");
        Bundle mBundle = intent.getExtras();
        if (mBundle != null) {
            String uri = "";
            int pageIndex = -1;
            try {
                JSONObject pushData = new JSONObject(intent.getStringExtra(MyPushReceiver.EXTRA_PARSE_DATA));
                log.d("VTT>>> onPushOpen  pushData" + pushData);
                
                // active page index param
                if (pushData.has("page_index")) {
                    pageIndex = pushData.getInt("page_index");
                    if(pageIndex > -1 && pageIndex < mPageMap.size()){
                        mJazzyViewPager.setCurrentItem(pageIndex);
                    }
                }

                // uri for show detail of new event, it will open DetailActivity
                if (pushData.has("uri")) {
                    uri = pushData.getString("uri");
                    if(!TextUtils.isEmpty(uri)){
                        // trigger event look like on item click
                        onYoutubeItemSelected(uri);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        log.d("VTT>>> onNewIntent " + intent.getExtras());
        checkPushGCM(intent);
    }
    
    /**
     * khoi tao jazzy view pager
     * 
     * @param actionBar
     */
    private void setupJazzyViewPager(TransitionEffect effect) {
        log.d("VTT>>> setupJazzyViewPager effect " + effect.toString());
        setTransitionEffect(effect);
        
        mJazzyViewPager = (JazzyViewPager) findViewById(R.id.jazzy_pager);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mJazzyViewPager.setTransitionEffect(effect);
        // mJazzyViewPager.setFadeEnabled(true);
        // mJazzyViewPager.setFadingEdgeLength(20);
        // mJazzyViewPager.setAlpha(0.8f);
        mJazzyViewPager.setOffscreenPageLimit(2);
        mJazzyViewPager.setAdapter(mSectionsPagerAdapter);
        
        // change background
        changeBackground();
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        actionBar.setDisplayHomeAsUpEnabled(false);
    }

	
	@Override
	public void onYoutubeItemSelected(String link) {
	    log.d("VTT>>> onRssItemSelected " + link);
		DetailFragment fragment = (DetailFragment) getSupportFragmentManager().findFragmentById(R.id.detailFragment);
		// dieu kien nay dung cho truong hop table co san fragment detail trong land layout
		if (fragment != null && fragment.isInLayout()) {
			fragment.loadUrl(link);
		} else {
			Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
			intent.putExtra(DetailActivity.EXTRA_URL, link);
			//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    if (item.getItemId() == android.R.id.home) {
	        if(mSlidingMenu.isMenuShowing()){
	            mSlidingMenu.showContent();
	        } else {
	            mSlidingMenu.showMenu();
	        }
	        return true;
        }
	    
	    return super.onOptionsItemSelected(item);
	}
	
	class SectionsPagerAdapter extends FragmentStatePagerAdapter {
	    
		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Object obj = super.instantiateItem(container, position);
			mJazzyViewPager.setObjectForPosition(obj, position);
			return obj;
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			if(object != null){
		        return ((Fragment)object).getView() == view;
		    }else{
		        return false;
		    }
		}
		
        @Override
        public Fragment getItem(int position) {
            log.d("VTT>>> Fragment getItem " + position);
            return BaseMainFragment.newInstance(position, mPageMap.get(position).searchKey);
        }
        
        @Override
        public CharSequence getPageTitle(int position) {
            return mPageMap.get(position).title;
        }

		@Override
		public int getCount() {
			return mPageMap.size();
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
		    try {
		        super.destroyItem(container, position, object);
		        mJazzyViewPager.delObjectForPosition(position);
            } catch (Exception e) {
                VttGA.sendException(mContext, "destroyItem " + e.getMessage());
            }
		}
	}
	
	/**
	 * on left menu item click event handler
	 * @param v
	 */
	public void onLeftMenuItemClicked(View v){
	    switch (v.getId()) {
        case R.id.menu_left_facebook:
            VttGA.sendEvent(mContext, "Left Menu Clicked", "Vlab FB", null, 0);
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/712469245492778"));
                startActivity(intent);
            } catch(Exception e) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.facebook.com/vlabsmartapp")));
            }
            break;
        case R.id.menu_left_bangxephang:
            VttGA.sendEvent(mContext, "Left Menu Clicked", "Bang Xep hang", null, 0);
            Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
            intent.putExtra(DetailActivity.EXTRA_URL, getString(R.string.url_bangxephang));
            startActivity(intent);
            break;
        case R.id.menu_left_xemtivi:
            openPageTV();
            break;
        case R.id.menu_left_xem_video:
            openPageVideo();
            break;
        case R.id.menu_left_setting_page_animation:
            setupPageTransition();
            break;
        default:
            VttGA.sendEvent(mContext, "Left Menu Clicked", "Góp ý chức năng mới", null, 0);
            VttUtils.openGooglePlayMarket(mContext, mContext.getPackageName());
            break;
        }
	}

    /**
     * open page watch TV
     */
    public void openPageTV() {
        VttGA.sendEvent(mContext, "Left Menu Clicked", "Xem TV", null, 0);
        Intent intentTv = new Intent(getApplicationContext(), DetailActivity.class);
        intentTv.putExtra(DetailActivity.EXTRA_URL, getString(R.string.url_xemtivi));
        startActivity(intentTv);
    }
    
    /**
     * open page watch video
     */
    public void openPageVideo() {
        VttGA.sendEvent(mContext, "Left Menu Clicked", "Xem Video", null, 0);
        Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
        intent.putExtra(DetailActivity.EXTRA_URL, getString(R.string.url_video_thethao));
        startActivity(intent);
    }

    /**
     * setup page transition
     */
    private void setupPageTransition() {
        int selectedIndex = mSharedPreferences.getInt(Constants.SHARE_CURRENT_TRANSITION_INDEX, DEFAULT_TRANSITION_INDEX);
        mDialogManager.showAnimationSettingDialog(selectedIndex, new IListDialogListener() {
            @Override
            public void onItemClicked(int position, String itemName) {
                // TODO
                log.d("VTT>>> onItemClicked " + position);
                VttGA.sendEvent(mContext, "Page Transition onItemClicked", itemName, null, 0);
                mSharedPreferences.edit().putInt(Constants.SHARE_CURRENT_TRANSITION_INDEX, position).commit();
                TransitionEffect effect = TransitionEffect.valueOf(itemName);
                setupJazzyViewPager(effect);
            }
        });
    }
	
    /**
     * change background image
     */
    public void changeBackground() {
        int transitionIndex = mSharedPreferences.getInt(Constants.SHARE_CURRENT_TRANSITION_INDEX, DEFAULT_TRANSITION_INDEX);
        if(transitionIndex == 0){
            mImgBackground.setVisibility(View.GONE);
        } else {
            mImgBackground.setVisibility(View.VISIBLE);
            mImgBackground.setImageResource(CommonHashMap.getRandomBackgroundId());
        }
    }

    private TransitionEffect getTransitionEffect() {
        String effect = mSharedPreferences.getString(Constants.SHARE_TRANSITION_EFFECT, TransitionEffect.CubeOut.toString());
        VttGA.sendEvent(mContext, "Get TransitionEffect", effect, null, 0);
        return TransitionEffect.valueOf(effect);
    }
    
    private void setTransitionEffect(TransitionEffect effect){
        mSharedPreferences.edit().putString(Constants.SHARE_TRANSITION_EFFECT, effect.toString()).commit();
    }
	
	@Override
	public void onBackPressed() {
	    
	    if (mSlidingMenu.isMenuShowing()) {
	        mSlidingMenu.showContent();
	        return;
        } 
	    
		int currentItem = mJazzyViewPager.getCurrentItem();
		Fragment fragmentItem = (Fragment) mSectionsPagerAdapter.instantiateItem(mJazzyViewPager, currentItem);
		
		if(fragmentItem != null && fragmentItem instanceof BaseWebFragment){
			((BaseWebFragment)fragmentItem).goBackWebView();
		} else {
		    // start app
		    // startAppAd.onBackPressed();
			finish();
		}
	}

}
